import { apiClient } from "@/lib/api-client";
import type { ApiResponse } from "@/lib/types/api";
import booksData from "@/lib/books.json";

interface Quote {
  content: string;
  author: string;
}

interface Book {
  title: string;
  author: string;
  description: string;
  link: string;
  coverUrl: string;
  tags: string[];
  rating: number;
  category?: "psychology" | "physical";
}

interface YiyanResponse {
  code: number;
  msg: string;
}

export class QuoteService {
  static async getDailyQuote(): Promise<ApiResponse<Quote>> {
    try {
      const response = await fetch(
        "https://cn.apihz.cn/api/yiyan/api.php?id=10001300&key=d54c24654c7636a6c93f490f334c060e"
      );
      const data: YiyanResponse = await response.json();

      if (data.code === 200) {
        return {
          status: true,
          data: {
            content: data.msg,
            author: "每日心语",
          },
        };
      }

      return {
        status: false,
        message: "获取每日心语失败",
      };
    } catch (error) {
      return {
        status: false,
        message: "获取每日心语失败",
      };
    }
  }

  static async getRecommendedBooks(): Promise<ApiResponse<Book[]>> {
    try {
      // 从 JSON 文件中获取书籍数据
      const books = booksData.data;

      // 为每本书添加分类
      const categorizedBooks = books.map((book, index) => ({
        ...book,
        // 前10本是心理健康类，后面的是身体健康类
        category: index < 10 ? ("psychology" as const) : ("physical" as const),
      }));

      // 按评分排序
      const sortedBooks = categorizedBooks.sort((a, b) => {
        if (a.category === b.category) {
          return b.rating - a.rating;
        }
        return a.category === "psychology" ? -1 : 1;
      });

      return {
        status: true,
        data: sortedBooks,
      };
    } catch (error) {
      return {
        status: false,
        message: "获取推荐书籍失败",
      };
    }
  }
}
